<?php
/**
 * A permission driver that is not simple just is_allowed or no_allowed.
 * So this is a good example of a bit complex permision driver.However this driver is
 * basically manging module administration page asscess.
 *
 * @author Ishtiaque Shahrier <md.ishtiaque@newgenbd.net>
 * @package acl
 * @subpackage drivers
 */
class driver_module_permission extends a_base_permission_driver_l_acl {

    /**
     *
     * @param a_model2data_converter $permission_data
     * @param int $user_id user id
     * @param int $group_id permission groups id user belongs to
     */
    public function __construct(a_model2data_converter $permission_data, $user_id, $group_id) {
        parent::__construct($permission_data, $user_id, $group_id);
    }

    public function run($param = NULL) {
        if ($param === NULL) {
            return FALSE;
        } else {
            return
                    $this->db()
                    ->where("acl_group_id", $this->group_id)
                    ->where("module_name", $param)
                    ->get("acl_module_access_permissions")
                    ->num_rows() > 0 ? TRUE : FALSE;
        }
    }
    /**
     * Returns list of modules.this function is used in the administration page
     * to list the modules for a group.
     * 
     * @param int $group_id
     * @return array
     */
    public static function get_modules($group_id=NULL) {
        $results = NULL;
        $acls = array();
        if($group_id!==NULL){
            $db = get_instance()->db;
            $query = $db->where("acl_group_id", $group_id)->get("acl_module_access_permissions");
            $results = $query->num_rows() > 0 ? $query->result() : NULL;
            if ($results!==NULL) {
                foreach ($results as $a)
                    $acls[$a->module_id] = $a;
            }
        }
        $modules = Module_Extended::list_modules();
        foreach ($modules as &$m) {
            if(isset($acls[$m->id])){
                $m->has_permission = "1";
            }else{
                $m->has_permission = "0";
            }
        }
        //debug_dump($modules);
        return $modules;
    }

    public static function enlable_diable_permission($module_id, $group_id,$flag){
        $db = get_instance()->db;
        if($flag){
            $db->query("DELETE FROM acl_module_access_permissions WHERE module_id = '$module_id' AND  acl_group_id = '$group_id' ");
            $db->query("INSERT INTO acl_module_access_permissions (module_id, acl_group_id)
                        VALUES( '$module_id', '$group_id')");
        }else{
            $db->query("DELETE FROM acl_module_access_permissions WHERE module_id = '$module_id' AND  acl_group_id = '$group_id' ");
        }
    }

}

?>